package com.sbox.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public abstract class BaseDAO <T>
{
	protected SQLiteDatabase mDatabase = null;
	
	public void setDatabase(SQLiteDatabase db)
	{
		mDatabase = db;
	}
	
	public abstract T[] createRows(Cursor c);
	
	public abstract T mapRow(Cursor c);
	
	public T[] mapRows(Cursor c)
	{
		int i=0;
		T[] items = null;
		
		if( c.getCount() == 0 )
		{
			return null;
		}
		
		items = createRows(c);
		
		if( !c.moveToFirst() )
			return null;
		
		while(true)
		{	
			items[i++] = mapRow(c);
			if( !c.moveToNext() )
			{
				break;
			}
		}
		
		return items;
	}
	
	public int getInt(Cursor c, String field)
	{
		int index = c.getColumnIndex(field);
		if( index == -1 )
		{
			return 0;
		}
		
		return c.getInt(index);
	}
	
	public long getLong(Cursor c, String field)
	{
		int index = c.getColumnIndex(field);
		if( index == -1 )
		{
			return 0;
		}
		
		return c.getLong(index);
	}
	
	public String getString(Cursor c, String field)
	{
		int index = c.getColumnIndex(field);
		if( index == -1 )
		{
			return "";
		}
		
		return c.getString(index);
	}
}
